<template>
  <div class="card-container">
    <el-card style="max-width: 100%">
      <el-button
        type="primary"
        v-has="`btn.Trademark.add`"
        @click="addBrand"
        style="margin-bottom: 10px"
      >
        添加品牌
      </el-button>
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column align="center" type="index" label="序号" width="80" />
        <el-table-column prop="tmName" label="品牌名称" width="180" />
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <!-- {{ row }} -->
            <img :src="row.logoUrl" width="60px" height="60px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <!-- {{ row }} -->
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="Edit(row)"
            >
              修改
            </el-button>
            <el-popconfirm
              width="250px"
              icon="Delete"
              icon-color="red"
              :title="`确定要删除${row.tmName}`"
              @confirm="Delete(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9]"
        :small="small"
        :pager-count="9"
        :background="background"
        layout=" prev, pager, next, jumper,->,total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="Trademark"
      />
      <el-dialog
        v-model="dialogFormVisible"
        :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
        width="500"
      >
        <el-form
          style="width: 80%"
          :model="trademarkParams"
          :rules="rules"
          ref="formRef"
        >
          <el-form-item
            prop="tmName"
            label="品牌名称"
            placeholder="请您输入品牌名称"
            label-width="80px"
          >
            <el-input v-model="trademarkParams.tmName" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="logoUrl" label="品牌LOGO" label-width="80px">
            <!-- 上传图片记得要带上api，否则无法上传，因为不能反向代理 -->
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="trademarkParams.logoUrl"
                :src="trademarkParams.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="Cancel">取消</el-button>
            <el-button type="primary" @click="Confirm">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, UploadProps } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type'
// 当前的页码
const currentPage = ref<number>(1)
// 每页显示的条数
const pageSize = ref<number>(3)
const small = ref(false)
const background = ref(true)
//存储已有品牌数据总数
let total = ref<number>(0)
//存储已有品牌的数据
let tableData = ref<Records>([])
let formRef = ref()
const dialogFormVisible = ref<boolean>(false)
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
onMounted(() => {
  Trademark()
})
const Trademark = async (page = 1) => {
  currentPage.value = page
  let result: TradeMarkResponseData = await reqHasTrademark(
    currentPage.value,
    pageSize.value,
  )
  if (result.code === 200) {
    // console.log(result)
    total.value = result.data.total
    tableData.value = result.data.records
  }
}
// 删除品牌
const Delete = async (id: number) => {
  let result: any = await reqDeleteTrademark(id)
  console.log('Delete', result)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    Trademark(
      tableData.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败！',
    })
  }
}
// 修改品牌
const Edit = (data: any) => {
  trademarkParams.id = data.id
  trademarkParams.tmName = data.tmName
  trademarkParams.logoUrl = data.logoUrl
  // console.log('Edit', data)
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
// 提交添加的品牌
const Confirm = async () => {
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  console.log(result)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    dialogFormVisible.value = false
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    dialogFormVisible.value = false
  }
  Trademark(trademarkParams.id ? currentPage.value : 1)
}
// 添加品牌
const addBrand = () => {
  trademarkParams.tmName = ''
  trademarkParams.id = 0
  trademarkParams.logoUrl = ''
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
const Cancel = () => {
  dialogFormVisible.value = false
}

const handleSizeChange = () => {
  Trademark()
}
// 上传文件之前的钩子，参数为上传的文件， 若返回false或者返回 Promise 且被 reject，则停止上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile);
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 > 4) {
      ElMessage({
        type: 'error',
        message: '上传的图片大小不能超过4MB',
      })
      return false
    } else {
      return true
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的图片格式必须是png、jpeg、gif',
    })
    return false
  }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  trademarkParams.logoUrl = response.data
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}
const validatorTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称不能少于2个字符'))
  }
  // console.log(rule,value,callback);
}
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  // console.log(123);
  if (value) {
    callback()
  } else {
    callback(new Error('请务必上传品牌LOGO'))
  }
  // console.log(rule,value,callback);
}
// 表单校验规则
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}
</script>
<script lang="ts">
export default {
  name: 'Trademark',
}
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
